<template>
  <!-- 内容 -->
  <div class="taskManagement_container">
    <div class="tm_c_wrap">
      <!-- 左边导航 -->
      <div class="tm_c_menu">
        <div class="tm_c_menu_option">
          <div class="tm_c_menu_top">
            <div class="tm_c_menu_top_title">平台</div>
          </div>
        </div>
        <!-- 列表 -->
        <div class="tm_c_menu_list">
          <div
            class="item"
            v-for="(item, index) in platformList"
            :class="platformListActive.id === item.id ? 'itemActive' : ''"
            :key="index"
            @click="routeTo(item.id)"
          >
            <div>{{ item.name }}</div>
          </div>
        </div>
      </div>
      <!-- 右边表格 -->
      <div class="tm_c_table">
        <div class="setOfLayer">
          <div>
            <el-row>
              <el-col :span="16" style="padding: 12px 0">
                <span style="font-size: 16px">{{ platformListActive.name }}</span>
              </el-col>
            </el-row>
          </div>
          <!-- 备注说明 -->
          <div class="remarks_box">
            {{ platformListActive.description }}
          </div>
          <!-- 表格 -->
          <div class="table_layout fixedLayer">
            <div class="setOfLayer send-param">
              <el-row style="border-bottom: 0; padding-bottom: 0">
                <el-col :span="24">
                  <el-tabs v-model="selectedMessageType">
                    <el-tab-pane
                      v-for="item in messageTypes"
                      :label="item.name"
                      :name="item.id"
                      :key="item.id"
                    ></el-tab-pane>
                  </el-tabs>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  选择配置：
                  <el-select
                    v-model="sendMessageParam.configIds"
                    multiple
                    placeholder="请选择配置..."
                  >
                    <el-option
                      v-for="item in configList"
                      :key="item.configId"
                      :label="item.configName"
                      :value="item.configId"
                    >
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
              <div v-for="item in selectedMessageTypeFields" :key="item.key">
                <el-row v-if="item.type === 'MULTI_OBJ_INPUT'">
                  <el-col :span="24">
                    <multiObjInput
                      :headers="item.multiObjFields"
                      @change="multiObjChange($event, item.key)"
                      :title="item.name"
                      v-model="sendMessageParam.param[item.key]"
                    />
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'RECEIVER_GROUP'">
                  <el-col :span="24">
                    选择分组：
                    <el-select
                      v-model="sendMessageParam.param[item.key]"
                      multiple
                      placeholder="请选择分组..."
                    >
                      <el-option
                        v-for="item in groups"
                        :key="item.id"
                        :label="item.groupName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'BOOLEAN'">
                  <el-col :span="24">
                    <el-checkbox v-model="sendMessageParam.param[item.key]">{{
                      item.description || item.name
                    }}</el-checkbox>
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'SELECT'">
                  <el-col :span="24">
                    {{ item.name }}：
                    <el-select
                      size="small"
                      placeholder="请选择..."
                      v-model="sendMessageParam.param[item.key]"
                    >
                      <el-option
                        v-for="option in item.options"
                        :key="option.id"
                        :label="option.name"
                        :value="option.id"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'RECEIVER'">
                  <el-col :span="12">
                    <el-input
                      size="small"
                      clearable
                      v-model="sendMessageParam.param[item.value]"
                      ref="inputReceiverId"
                      @keyup.enter.native="handleAddReceiverId(item)"
                      :placeholder="item.description || item.name"
                    >
                    </el-input>
                  </el-col>
                  <el-col :span="12">
                    <el-button
                      type="text"
                      size="small"
                      @click="handleClearAddReceiverId(item)"
                      >清空</el-button
                    >
                    <span v-show="false">{{
                      sendMessageParam.param[item.key]
                    }}</span>
                  </el-col>
                  <el-col :span="24">
                    <el-tag
                      style="margin-bottom: 2px; margin-left: 2px"
                      v-for="addId in sendMessageParam.param[item.key]"
                      size="small"
                      :key="addId"
                      @close="handleAddReceiverIdClose(item, addId)"
                      closable
                      :type="'info'"
                    >
                      {{ addId }}
                    </el-tag>
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'STRING'">
                  <el-col :span="24">
                    <el-input
                      size="small"
                      type="text"
                      clearable
                      v-model="sendMessageParam.param[item.key]"
                      :placeholder="item.description || item.name"
                    >
                    </el-input>
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'TEXTAREA'">
                  <el-col :span="24">
                    <el-input
                      type="textarea"
                      clearable
                      :autosize="{ minRows: 15, maxRows: 100 }"
                      v-model="sendMessageParam.param[item.key]"
                      :placeholder="item.description || item.name"
                    >
                    </el-input>
                  </el-col>
                </el-row>
                <el-row v-if="item.type === 'EMAIL_FILE'">
                  <el-col :span="24">
                    <el-upload
                      class="upload-demo"
                      action=""
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      multiple
                      :limit="1"
                      :file-list="fileList"
                      :http-request="uploadData">
                      <el-button size="small" type="primary"
                        >选择文件</el-button
                      >
                    </el-upload>
                  </el-col>
                </el-row>
              </div>
              <el-row
                style="border-bottom: 0; border-top: 1px solid #c3c6cc;position: -webkit-sticky;position: sticky; bottom: 0; background: white; ">
                <el-col :span="24">
                  <el-button size="mini" type="primary" @click="messagePush"
                    >发送</el-button
                  >
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  msgPush,
  list,
  getPlatformType,
  getMessageField,
  getPlatform,
  emailUpload
} from "@/api/messageApi";

import { Message } from "element-ui";
import Vue from 'vue';

export default {
  components: {
    multiObjInput: () => import('./component/multiObjInput.vue'),
  },
  data() {
    return {
      //文件名列表 上传文件后把fileName放到这里面
      fileNames: [],
      fileList: [],
      // 选中的平台
      platformListActive: {},
      // 可选择的配置
      configList: [],
      // 可选的消息类型
      messageTypes: [],
      // 选择的消息类型
      selectedMessageType: "",
      // 选择的消息类型的所有字段
      selectedMessageTypeFields: [],
      // 左边平台列表
      platformList: [],
      configId: 0,
      isConfigDailog: false,
      deleteName: "",
      deleteDialogVisible: false,
      taskGroupIds: "",
      isGroup: true,
      inputReceiverId: "", // 当前新增的接收人
      addReceiverIds: [], // 新增的接收人
      // 发送消息参数
      sendMessageParam: {
        configIds: [],
        param: {},
      },
      showHisDetailDialog: false,
      requestNo: "",
      schemeList: [],
      selectedScheme: null,
      dialogManageSchemeVisible: false,
      taskVisible: false,
      isTaskDialog: false,
      taskParamProps: null,
    };
  },
  watch: {
    // 切换消息类型
    selectedMessageType(val) {
      if (!val || val === "0") {
        return;
      }
      this.initParam();
      this.changeMessageType();
    },
  },
  methods: {
    initParam() {
      this.sendMessageParam.configIds = [];
      this.sendMessageParam.param = {};
      this.addReceiverIds = []; // 新增的接收人
    },
    multiObjChange($event, key) {
      console.log($event);
      this.sendMessageParam.param[key] = $event;
      this.$forceUpdate();
    },
    handleAddReceiverId(item) {
      let reg = new RegExp(this.platformListActive.validateReg);
      let validate = reg.test(this.inputReceiverId);
      if (!validate) {
        Message.error("格式校验不正确");
      }
      this.sendMessageParam.param[item.key] =
        this.sendMessageParam.param[item.key] || [];
      if (!this.sendMessageParam.param[item.value] || this.sendMessageParam.param[item.key].indexOf(this.inputReceiverId) >= 0 ||!validate) {
        return;
      }
      this.sendMessageParam.param[item.key].push(this.sendMessageParam.param[item.value]);
      console.log(this.sendMessageParam);
      this.sendMessageParam.param[item.value] = "";
    },
    handleClearAddReceiverId(item) {
      this.sendMessageParam.param[item.key] = [];
      this.$forceUpdate();
    },
    handleAddReceiverIdClose(item, addId) {
      this.sendMessageParam.param[item.key] = this.sendMessageParam.param[item.key] || [];
      this.sendMessageParam.param[item.key].splice(this.sendMessageParam.param[item.key].indexOf(addId),1);
      this.$forceUpdate();
    },
    async queryPlatformType() {
      //查某一个平台支持的消息类型
      let res = await getPlatformType(this.platformListActive.id);
      this.messageTypes = res.data;
      //默认取第一个展示 watch里面做查询
      this.selectedMessageType = res.data[0].id;
      //查询平台的配置
      this.queryPlatformConfig();
    },
    async queryPlatformConfig() {
      //查某一个平台支持的消息类型
      let res = await list(this.platformListActive.id);
      this.configList = res.data;
    },
    async init() {
      let res = await getPlatform();
      //默认选择第一个平台 这里平台数据是写死的 也可以从改成从后端获取
      this.platformList = res.data;
      this.platformListActive = this.platformList[0];
      this.queryPlatformType();
    },
    //平台路由
    routeTo(platform) {
      if (platform) {
        for (const m of this.platformList) {
          if (m.id === platform) {
            this.platformListActive = m;
            this.configList = [];
            this.sendMessageParam.configIds = [];
            this.sendMessageParam.param = {};
            this.queryPlatformType();
            return;
          }
        }
      }
    },
    // 切换消息类型
    async changeMessageType() {
      let res = await getMessageField(this.selectedMessageType);
      this.selectedMessageTypeFields = res.data;
      this.selectedScheme = null;
      //   this.refreshScheme()
      //   this.initParam()
    },
    async messagePush() {
      if (!this.sendMessageParam.configIds.length) {
        Message.error("请选择至少一个配置");
        return;
      }
      if (this.platformListActive.id == 'EMAIL') {
          //设置文件
          Vue.set(this.sendMessageParam.param, "fileNames", this.fileNames)
      }
      let param = {};
      param[this.selectedMessageType] = {
        ...this.sendMessageParam,
      };
      console.log(this.sendMessageParam)
      let res = await msgPush({
        messageParam: param,
      });
      let that = this;
      const h = this.$createElement;
      this.$msgbox({
        title: "结果",
        message: h("p", null, [
          h("span", null, "消息投递成功，请求号：" + res.data),
        ]),
        showCancelButton: true,
        confirmButtonText: "查看日志",
        cancelButtonText: "知道了",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            that.requestNo = res.data;
            this.showHisDetailDialog = true;
          }
          done();
        },
      }).then((action) => {});
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    async uploadData(file) {
      let formData = new FormData();
      formData.append('file', file.file); //文件对象
      let res = await emailUpload(formData);
      if (200 == res.code) {
        this.fileNames.push(res.data.fileName)
      }
    }
  },
  mounted: function () {
    //加载数据
    this.init();
  },
};
</script>
<style lang="less" scoped>
.taskManagement_container {
  height: 100%;
  display: flex;
  flex-direction: column;
  // background-color: #fff;
  overflow-y: auto;
  box-sizing: border-box;
  .tm_c_wrap {
    width: 100%;
    height: 100%;
    display: flex;
    .tm_c_menu {
      width: 240px;
      border-radius: 4px;
      background-color: #fff;
      height: 100%;
      margin-right: 16px;
      padding: 10px 16px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      .tm_c_menu_option {
        .tm_c_menu_top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-bottom: 10px;
          .tm_c_menu_top_title {
            font-size: 16px;
            font-weight: 500;
            color: rgba(29, 35, 52, 1);
          }
        }
      }
      .tm_c_menu_list {
        flex: 1;
        overflow-y: auto;
        .item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 10px;
          width: calc(100% - 10px);
          height: 32px;
          background: rgba(232, 236, 242, 1);
          border-radius: 4px;
          font-size: 12px;
          margin: 5px;
          line-height: 32px;
          text-align: center;
          font-weight: 400;
          color: #656975;
          box-sizing: border-box;
          cursor: pointer;
          div {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          &:hover {
            background: rgba(0, 120, 255, 1);
            color: rgba(255, 255, 255, 1);
          }
        }
        .itemActive {
          width: calc(100% - 10px);
          height: 32px;
          background: rgba(0, 120, 255, 1);
          border-radius: 4px;
          font-size: 12px;
          font-weight: 400;
          line-height: 32px;
          text-align: center;
          margin: 5px;
          color: rgba(255, 255, 255, 1);
        }
      }
    }
    .tm_c_table {
      height: 100%;
      width: 100%;
      flex: 1;
      overflow-y: auto;
      padding: 10px 16px;
      box-sizing: border-box;
      background-color: #fff;
      border-radius: 4px;
      .features {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title {
          font-size: 20px;
          font-weight: 500;
          color: rgba(29, 35, 52, 1);
        }
        .features_right {
          display: flex;
          align-items: center;
          /deep/ .el-input-group {
            width: auto;
          }
          .addTask {
            flex-shrink: 0;
            margin-left: 10px;
            cursor: pointer;
            color: rgba(0, 120, 255, 1);
            font-size: 16px;
            font-weight: 500;
          }
        }
      }
      .remarks_box {
        padding: 5px 0;
        font-size: 12px;
        font-weight: 400;
        color: rgba(101, 105, 117, 1);
        display: flex;
        border-bottom: 1px solid rgba(195, 198, 204, 1);
        .item {
          border-right: 1px solid rgba(101, 105, 117, 0.5);
          margin-right: 20px;
          padding-right: 20px;
          &:last-child {
            border-right: none;
          }
        }
      }
      .table_layout {
        flex: 1;
        margin-top: 15px;
        margin-left: 50px;
        margin-right: 50px;
        overflow-y: auto;
      }
    }
  }
}
.setOfLayer {
  display: flex;
  flex-direction: column;
  height: 100%;
  .fixedLayer {
    flex: 1;
    overflow-y: auto;
  }
}
.table_page {
  text-align: center;
  padding-top: 10px;
}
.preState {
  display: inline-block;
  padding-left: 10px;
}
.info {
  color: #909399;
}
.success {
  color: #67c23a;
}
.primary {
  color: #409eff;
}
.operating {
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 120, 255, 1);
  display: inline-block;
  padding: 0 5px;
  cursor: pointer;
}
.danger {
  color: #f56c6c;
}
.optionIng {
  display: flex;
  span {
    margin-right: 15px;
  }
}
.el-table {
  overflow: auto;
}
.el-table__header-wrapper,
.el-table__body-wrapper,
.el-table__footer-wrapper {
  overflow: visible;
}
.el-table__body-wrapper {
  overflow-x: visible !important;
}
.send-param .el-row {
  padding-bottom: 10px;
  padding-top: 10px;
  border-bottom: 1px solid #c3c6cc;
}
</style>
<style scoped>
.send-param >>> .el-textarea__inner {
  border: 0;
  resize: none;
}
.send-param >>> .el-input__inner {
  border: 0;
}
</style>
